<?php

namespace App\Exceptions;

use Exception;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Support\Facades\Log;
use Prophecy\Exception\Doubler\MethodNotFoundException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class Handler extends ExceptionHandler
{
    //以下定义的变量是响应给客户端的
    public $code;
    public $msg;
    public $errorCode;
    public $status;
    /**
     * A list of the exception types that are not reported.
     *
     * @var array
     */
    protected $dontReport = [
        //
    ];

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array
     */
    protected $dontFlash = [
        'password',
        'password_confirmation',
    ];

    /**
     * Report or log an exception.
     *
     * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
     *
     * @param  \Exception $exception
     * @return void
     */
    public function report(Exception $exception)
    {

        parent::report($exception);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Exception $exception
     * @return \Illuminate\Http\Response
     */
    public function render($request, Exception $exception)
    {

        if ($exception instanceof BaseException) { //判断为自定义异常时
            header("HTTP/1.0 400");
            $this->code = $exception->code;//将BaseException中的值赋值给成员变量，最后进行输出
            $this->msg = $exception->msg;
            $this->errorCode = $exception->errorCode;
            $this->status = $exception->status;
        } else if ($exception instanceof NotFoundHttpException) {//访问路径不存在
            $this->code = -1;
            $this->msg = "请求路径不存在";
            $this->errorCode = -1;
            $this->status = 0;
        } else {//其他错误
            if (config('app.debug')) {//判断是否为调试模式，
                //返回默认界面
                return parent::render($request, $exception);
            } else {
                //返回json数据
                $this->code = 500;
                $this->msg = "服务器内部错误";
                $this->errorCode = 999;
                $this->status = 0;
                $this->recordLog($exception);//日志记录
            }
        }
        $result = [
            "responseMessage" => $this->msg,
            "responseCode" => $this->errorCode,
            "data" => []
        ];
        exit(json_encode($result, $this->code));
    }

    private function recordLog(Exception $e)
    {
        Log::channel('myLog')->error($e);
    }
}
